/**
 * Hook用法
 */
import React, {useState} from "react";

function fetchTodos() {
    return [
        {
            id: 1,
            title: '吃饭',
            completed: false
        },
        {
            id: 2,
            title: '刷牙',
            completed: false
        },
        {
            id: 3,
            title: '睡觉',
            completed: true
        },
    ]
}

function TodoItem(props) {
    return (
        <li key={props.id}>
            <input type="checkbox" defaultChecked={props.completed} onChange={props.onToggle}/>
            <label style={{textDecoration: props.completed ? 'line-through 4px': 'none'}}>{props.title}</label>
            <button onClick={props.onDelete}>删除</button>
        </li>
    )
}

function ShowLoading(props) {
    if(props.Loading) {
        return (
            <div>Loading...</div>
        )
    }
    return (
        <div>Over</div>
    )
}

function List(props) {
    props.onFunction();
    // const todos = fetchTodos();
    // 管理状态，修改props的值
    const [todos, setTodos] = useState(fetchTodos())
    const todoItemTemp = todos.map((todo) =>
        (
            <TodoItem
                key={todo.id}
                title={todo.title}
                completed={todo.completed}
                onDelete={() => {
                    setTodos(todos.filter((x) => x.id !== todo.id))
                }}
                onToggle={() => {
                    setTodos(
                        todos.map((x) => x.id === todo.id ? {...x,completed: !x.completed} : x)
                    )
                }}
            />
        )
    )
    return (
        <div>
            <ul>{todoItemTemp}</ul>
            <ShowLoading Loading={props.Loading}/>
        </div>

    )
}

export default List;
